package com.app.business.service;

import com.app.business.calculate.CalculateUtils;
import com.app.business.en.Status;
import com.app.business.model.AdjustArea;
import com.app.business.model.Contract;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 面积调换管理
 * Created by ddz on 2019/2/12.
 */
@Service
public class AdjustAreaService extends JpaBaseDao<AdjustArea, Integer> {

    @Autowired
    private ContractService contractService;
    @Autowired
    private ActionHistoryService actionHistoryService;

    /**
     * 根据协议Id得到调剂记录
     *
     * @param contractId
     * @return
     */
    public List<AdjustArea> getAdjustAreaListByContractId(Integer contractId) {
        //查询语句
        String hql = " from AdjustArea aa where aa.contract.id = :contractId order by aa.doDate desc";
        Map<String, Object> map = new HashMap<>();
        map.put("contractId", contractId);
        return this.findHql(hql, map);
    }

    /**
     * 面积调剂保存
     *
     * @param request
     * @return
     */
    @Transactional
    public synchronized Response setAreaSave(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //得到转出方和接受方ID及协议
        int outContractId = ParamUtils.getInt(request, "outContractId", 0);
        int inContractId = ParamUtils.getInt(request, "inContractId", 0);
        String outCareBuyAreaNameType = ParamUtils.getString(request, "outCareBuyAreaNameType", "");
        String inCareBuyAreaNameType = ParamUtils.getString(request, "inCareBuyAreaNameType", "");
        //得到转出面积
        BigDecimal area = ParamUtils.getDecimal(request, "area", 0);
        Precondition.checkAjaxArguement(area.compareTo(BigDecimal.ZERO) > 0, "1111", "数据错误！");
        Precondition.checkAjaxArguement(outCareBuyAreaNameType != null && !outCareBuyAreaNameType.equals(""), "1111", "转出方面积类型数据错误！");
        Precondition.checkAjaxArguement(inCareBuyAreaNameType != null && !inCareBuyAreaNameType.equals(""), "1111", "转入方面积类型数据错误！");

        Contract outContract = this.contractService.findOne(outContractId);//转出方
        Contract inContract = this.contractService.findOne(inContractId);//转入方
        Precondition.checkAjaxArguement(area.compareTo(outContract.getLimitHouseAreaTotal()) <= 0, "1111", "转出面积超出转出方总可选房面积！");
        Precondition.checkAjaxArguement(outContract.getFinanceCheckStatus() != Status.YES.getIndex(), "2222", "转出方财务已复核，不能调换面积！");
//        Precondition.checkAjaxArguement(inContract.getFinanceCheckStatus() == Status.NO.getIndex(), "2222", "转入方财务已复核，不能调换面积！");
        //保存合并面积记录
        this.saveAdjustArea(outContract, inContract, outCareBuyAreaNameType, inCareBuyAreaNameType, area);


        //先判断面积，并保存转出方合为，
        Precondition.checkAjaxArguement(outContract.getChooseHouseStatus() == Status.NO.getIndex(), "2222", "转出方设置为已选房，不能进行合并！");
        Precondition.checkAjaxArguement(outContract.getChooseHouseAreaTotal().compareTo(BigDecimal.ZERO) > 0, "2222", "转出方未选房，不能进行合并！");

        this.contractService.save(outContract);

        /*合并是不做以下处理*/
        /*if (!inContract.getContractCode().contains(outContract.getContractCode())) {
            inContract.setContractCode(inContract.getContractCode() + "、" + outContract.getContractCode());
        }
        if (inCareBuyAreaNameType.equals("产权调换")) {
            inContract.setPropertyChangeArea(BigDecimalUtils.getSum(inContract.getPropertyChangeArea(), area));
            //判断照顾购买类型
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("可限量照顾购买安置部分")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("照顾购买安置部分")) {
            inContract.setCareBuyArea1(BigDecimalUtils.getSum(inContract.getCareBuyArea1(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("可限量增加安置部分")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("增量安置部分")) {
            inContract.setCareBuyArea2(BigDecimalUtils.getSum(inContract.getCareBuyArea2(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("低保户照顾购买")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("历史古街区店面部分增量安置")) {
            inContract.setCareBuyArea3(BigDecimalUtils.getSum(inContract.getCareBuyArea3(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("居住困难户保障安置")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("低保户照顾购买")) {
            inContract.setCareBuyArea4(BigDecimalUtils.getSum(inContract.getCareBuyArea4(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("未建合法宅基地照顾购买")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("居住困难户保障安置")) {
            inContract.setCareBuyArea5(BigDecimalUtils.getSum(inContract.getCareBuyArea5(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("房屋倒塌或只有房屋基础照顾购买")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("已批未建宅基地照顾购买")) {
            inContract.setCareBuyArea6(BigDecimalUtils.getSum(inContract.getCareBuyArea6(), area));
        } else if ((inContract.getCareBuyAreaNameType() == 1 && inCareBuyAreaNameType.equals("企业照顾购买")) ||
                inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("房屋倒塌宅基地照顾购买")) {
            inContract.setCareBuyArea7(BigDecimalUtils.getSum(inContract.getCareBuyArea7(), area));
        } else if (inContract.getCareBuyAreaNameType() == 2 && inCareBuyAreaNameType.equals("企业照顾购买")) {
            inContract.setCareBuyArea8(BigDecimalUtils.getSum(inContract.getCareBuyArea8(), area));
        }*/
        this.contractService.save(inContract);
        CalculateUtils.main(outContractId);
        CalculateUtils.main(inContractId);
        return new Response("0001", "保存成功");
    }

    /**
     * 保存双方记录
     *
     * @param outContract
     * @param inContract
     * @param area
     */
    @Transactional
    public void saveAdjustArea(Contract outContract, Contract inContract, String type, String inAreaType, BigDecimal area) {
        //得到操作人
        String doName = WebUtils.getLoginUserInfo().getName();
        //保存转出方记录
        AdjustArea adjustArea1 = new AdjustArea();
        adjustArea1.setAdjustArea(BigDecimalUtils.getBigAndBigSub(new BigDecimal("0"), area));
        adjustArea1.setContract(outContract);
        adjustArea1.setDoDate(new Date());
        adjustArea1.setDoName(doName);
        adjustArea1.setType(type);
        adjustArea1.setZjStatus(-1);//减少
        adjustArea1.setOutContractId(outContract.getId());
        adjustArea1.setInContractId(inContract.getId());
        String memo1 = DateUtils.dateToStringDefault1(new Date()) + "此选房号将" + "【" + area + "】㎡的" + type
                + "面积合并到选房号：" + inContract.getChooseHouseNum() + "，协议号：" + inContract.getContractCode() + "的" + inAreaType + "面积中。";
        adjustArea1.setMemo(memo1);
        this.save(adjustArea1);
        this.actionHistoryService.saveActionHistoryByContractId(outContract.getId(), memo1, "合并转出");

        //保存接受方记录
        AdjustArea adjustArea2 = new AdjustArea();
        adjustArea2.setAdjustArea(area);
        adjustArea2.setContract(inContract);
        adjustArea2.setDoDate(new Date());
        adjustArea2.setDoName(doName);
        adjustArea2.setType(inAreaType);
        adjustArea2.setZjStatus(1);//增加
        adjustArea2.setInContractId(inContract.getId());
        adjustArea2.setOutContractId(outContract.getId());
        String memo2 = DateUtils.dateToStringDefault1(new Date()) + "此选房号接收到选房号" + outContract.getChooseHouseNum() + "，协议号：" + outContract.getContractCode() +
                "的" + type + "面积" + "【" + area + "】㎡" + "到此选房号" + inAreaType + "面积中。";
        adjustArea2.setMemo(memo2);
        this.save(adjustArea2);
        this.actionHistoryService.saveActionHistoryByContractId(inContract.getId(), memo2, "合并转入");

    }

    /**
     * 删除对应删除的条数，一次性删除两条
     * @param adjustArea
     */
    @Transactional
    public synchronized void deleteAdjustAreaByMsg(AdjustArea adjustArea) {
        //查询语句
        String sql = "delete from adjust_area  where in_contract_id =:inContractId and out_contract_id =:outContractId and type =:type and ABS(adjust_area) =:adjustArea ";
        this.entityManager.createNativeQuery(sql)
                .setParameter("inContractId",adjustArea.getInContractId())
                .setParameter("outContractId",adjustArea.getOutContractId())
                .setParameter("type",adjustArea.getType())
                .setParameter("adjustArea",adjustArea.getAdjustArea().abs())//绝对值
                .executeUpdate();
    }
}